import { Injectable } from '@nestjs/common';
import * as fs from 'fs';
import * as path from 'path';

export interface News {
  id: string;
  title: string;
  content: string;
  author: string;
  tags: string[];
  views: number;
  createdAt: string;
  updatedAt: string;
}

@Injectable()
export class NewsService {
  private readonly newsFile = path.join(process.cwd(), 'data', 'news.json');

  constructor() {
    const dataDir = path.join(process.cwd(), 'data');
    if (!fs.existsSync(dataDir)) {
      fs.mkdirSync(dataDir, { recursive: true });
    }

    if (!fs.existsSync(this.newsFile)) {
      fs.writeFileSync(this.newsFile, JSON.stringify([]));
    }
  }

  private readNews(): News[] {
    const data = fs.readFileSync(this.newsFile, 'utf8');
    return JSON.parse(data);
  }

  private writeNews(news: News[]): void {
    fs.writeFileSync(this.newsFile, JSON.stringify(news, null, 2));
  }

  findAll(): News[] {
    return this.readNews();
  }

  findById(id: string): News | undefined {
    const news = this.readNews();
    return news.find(item => item.id === id);
  }

  create(newsData: Omit<News, 'id' | 'views' | 'createdAt' | 'updatedAt'>): News {
    const news = this.readNews();
    const newNews: News = {
      id: Date.now().toString(),
      ...newsData,
      views: 0,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    };
    news.push(newNews);
    this.writeNews(news);
    return newNews;
  }

  update(id: string, newsData: Partial<Omit<News, 'id' | 'createdAt'>>): News | null {
    const news = this.readNews();
    const index = news.findIndex(item => item.id === id);
    if (index === -1) return null;
    
    news[index] = {
      ...news[index],
      ...newsData,
      updatedAt: new Date().toISOString(),
    };
    
    this.writeNews(news);
    return news[index];
  }

  delete(id: string): boolean {
    const news = this.readNews();
    const initialLength = news.length;
    const filteredNews = news.filter(item => item.id !== id);
    this.writeNews(filteredNews);
    return filteredNews.length !== initialLength;
  }

  incrementViews(id: string): void {
    const news = this.readNews();
    const index = news.findIndex(item => item.id === id);
    if (index !== -1) {
      news[index].views += 1;
      this.writeNews(news);
    }
  }
}